const { blog, Op } = require('../model/index')

let fn_show = async (ctx) => {

    await blog.findAll().then(res => {
        ctx.body = res
    })

}

let fn_query = async (ctx) => {

    let keyword = ctx.request.query.keyword;
    if (keyword !== '') {
        if (isNaN(keyword) == false) {
            let data = await blog.findAll({
                where: {
                    [Op.or]: [
                        { id: keyword },
                        { abstract: keyword },
                        { content: keyword },
                        { classify: keyword },
                        { author: keyword },
                        { postedTime: keyword }
                    ]
                }
            })
            ctx.body = data

        } else {
            let data = await blog.findAll({
                where: {
                    [Op.or]: [
                        { abstract: keyword },
                        { content: keyword },
                        { classify: keyword },
                        { author: keyword },
                        { postedTime: keyword }
                    ]
                }
            })
            ctx.body = data
        }

    } else {
        await blog.findAll(
            {
                order: [
                    ['id', 'ASC']
                ]
            }
        ).then(res => {
            ctx.body = res
        })
    }
}


let fn_add = async (ctx) => {

    let data = await blog.findAll().then(res => {
        let max = 0;

        for (let i in res) {
            if (max < res[i].id) {
                max = res[i].id
            }
        }
        let id = max + 1;
        let data = ctx.request.body;
        data.id = id
        return data
    })

    await blog.create(data)

    await blog.findAll().then(res => {
        ctx.body = res
    })
}
let fn_edit = async (ctx) => {
    let data = ctx.request.body

    await blog.findByPk(data.id).then(async (post) => {
        await post.update(
            {
                id: data.id,
                title: data.title,
                abstract: data.abstract,
                content: data.content,
                classify: data.classify,
                author: data.author,
                postedTime: data.postedTime
            }
        )
    })


    await blog.findAll(
        {
            order: [
                ['id', 'ASC']
            ]
        }
    ).then(res => {
        ctx.body = res
    })
}

let fn_Deleted = async (ctx) => {

    let id = ctx.request.query.id;

    await blog.destroy({
        where: { id: id }
    })

    await blog.findAll(
        {
            order: [
                ['id', 'ASC']
            ]
        }
    ).then(res => {
        ctx.body = res
    })

}

let get = [['/show', fn_show], ['/query', fn_query], ['/indexDeleted', fn_Deleted]]
let post = [['/indexadd', fn_add], ['/indexedit', fn_edit]]

module.exports = {
    'GET': get,
    'POST': post
}
